import {postSysSysdictionaryDictionary as getDictionary} from '$my/code/api/sys-dictionary'
import dictionaryProps from './dictionary-props'
import {convertName} from './page-modules/util'

export default {
  loadDictionary({state, commit, dispatch}, path) {
    if (!path) return;
    const temp = path.split('/')
    let statePath = '', stateName = ''
    // 获取多层state的路径
    if (temp.length > 1) {
      statePath = temp.splice(0, temp.length - 1)
    }
    stateName = temp[0]

    let pathTemp = state
    statePath.forEach(n => {
      pathTemp = pathTemp[n]
    })

    if (pathTemp[stateName].length > 0) return

    const dictName = dictionaryProps[stateName] || stateName
    return getDictionary({type: dictName}).then(res => {
      const commitName = 'set' + convertName(stateName)
      statePath.push(commitName)
      if(res && Object.prototype.toString.call(res) === '[object Array]') {
        commit(statePath.join('/'), res)
      }
      return res
    })
  }
}
